package com.halobop.demo.admin.service.impl;

import com.halobop.demo.admin.dto.SMSSendDto;
import com.halobop.demo.admin.dto.SMSVerifyDto;
import com.halobop.demo.admin.service.ISMSService;
import com.halobop.demo.admin.utils.RedisUtil;
import com.halobop.demo.admin.utils.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class SMSServiceImpl implements ISMSService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SmsUtil smsUtil;

    @Value("${myRedis.key.prefix.authCode}")
    private String authCodePrefix;
    @Value("${myRedis.key.expire.authCode}")
    private long authCodeExpire;

    @Override
    public boolean sendAuthCode(SMSSendDto dto) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        redisUtil.set(authCodePrefix + dto.getPhoneNumber(), sb.toString());
        redisUtil.expire(authCodePrefix + dto.getPhoneNumber(), authCodeExpire);
        return smsUtil.sendAuthCode(dto.getPhoneNumber(), sb.toString());
    }

    @Override
    public boolean verifyAuthCode(SMSVerifyDto dto) {
        String authCode = (String) redisUtil.get(authCodePrefix + dto.getPhoneNumber());
        return dto.getAuthCode().equals(authCode);
    }
}
